package cn.controlsys.service.impl;

import cn.controlsys.common.constants.HttpConstant;
import cn.controlsys.common.entity.RequestResult;
import cn.controlsys.common.saiheyi.ParameterBuilder;
import cn.controlsys.common.saiheyi.SaiheyiConstants;
import cn.controlsys.dao.PaymentRecordMapper;
import cn.controlsys.dao.RechargeAccountMapper;
import cn.controlsys.model.PaymentRecord;
import cn.controlsys.model.RechargeAccount;
import cn.controlsys.pojo.WecbillpostVO;
import cn.controlsys.service.SaiheyiService;
import cn.controlsys.utils.DateUtils;
import cn.controlsys.utils.HttpClientResult;
import cn.controlsys.utils.HttpClientUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: Created by Administrator on 2018/12/20.
 */
@Service
public class SaiheyiServiceImpl implements SaiheyiService {
    private static Logger logger = LoggerFactory.getLogger(SaiheyiServiceImpl.class);
    @Autowired
    RechargeAccountMapper rechargeAccountMapper;
    @Autowired
    PaymentRecordMapper paymentRecordMapper;

    @Override
    public HttpClientResult wecbillpost(String productid, String wecaccount, String ymonth) {
        logger.info("[账单查询提交] 户号：{}，产品编号：{}，日期：{}", wecaccount, productid, ymonth);
        String stockordernumber = ParameterBuilder.getOutTradeNo(wecaccount);
        String timestamp = DateUtils.getCurrentDateStr();
        ParameterBuilder params = new ParameterBuilder();
        params.put("actionname", SaiheyiConstants.WEC_BILL_POST);
        params.put("partnerid", SaiheyiConstants.PARENT_ID);
        params.put("timestamp", timestamp);
        params.put("productid", productid); ////产品编号
        params.put("stockordernumber", stockordernumber); //商家订单号:商家订单号-中英文6~32位
        params.put("wecaccount", wecaccount); //水电煤缴费账号
        params.put("ymonth", ymonth); //年月
        String sign = params.sign(SaiheyiConstants.SIGN_KEY);
        Map<String, String> stringMap = new HashMap<String, String>();
        stringMap.put("actionname", SaiheyiConstants.WEC_BILL_POST);
        stringMap.put("partnerid", SaiheyiConstants.PARENT_ID);
        stringMap.put("timestamp", timestamp);
        stringMap.put("productid", productid); ////产品编号
        stringMap.put("stockordernumber", stockordernumber); //商家订单号:商家订单号-中英文6~32位
        stringMap.put("wecaccount", wecaccount); //水电煤缴费账号
        stringMap.put("ymonth", ymonth); //年月
        stringMap.put("sign", sign); //签名
        HttpClientResult httpClientResult = null;
        try {
            httpClientResult = HttpClientUtils.doPost(SaiheyiConstants.URL, stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpClientResult;
    }

    @Override
    public HttpClientResult wecbillquery(String stockordernumber) {
        logger.info("[账单查询] 商户订单号：{}", stockordernumber);
        String timestamp = DateUtils.getCurrentDateStr();
        ParameterBuilder params = new ParameterBuilder();
        params.put("actionname", SaiheyiConstants.WEC_BILL_QUERY);
        params.put("partnerid", SaiheyiConstants.PARENT_ID);
        params.put("timestamp", timestamp);
        params.put("stockordernumber", stockordernumber); //商家订单号:商家订单号-中英文6~32位
        String sign = params.sign(SaiheyiConstants.SIGN_KEY);
        Map<String, String> stringMap = new HashMap<String, String>();
        stringMap.put("actionname", SaiheyiConstants.WEC_BILL_QUERY);
        stringMap.put("partnerid", SaiheyiConstants.PARENT_ID);
        stringMap.put("timestamp", timestamp);
        stringMap.put("stockordernumber", stockordernumber); //商家订单号:商家订单号-中英文6~32位
        stringMap.put("sign", sign); //签名
        HttpClientResult httpClientResult = null;
        try {
            httpClientResult = HttpClientUtils.doPost(SaiheyiConstants.URL, stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return httpClientResult;
    }

    @Override
    public HttpClientResult wrecharge(String productid, String delayfee, String wecaccount, String wecbillmoney) {
        logger.info("[账单缴费] 户号：{}，产品编号：{}，账单金额：{},滞纳金：{}", wecaccount, productid, wecbillmoney, delayfee);
        String stockordernumber = ParameterBuilder.getOutTradeNo(wecaccount);
        System.out.println("stockordernumber:" + stockordernumber);
        String timestamp = DateUtils.getCurrentDateStr();
        ParameterBuilder params = new ParameterBuilder();
        params.put("actionname", SaiheyiConstants.WEC_RECHARGE);
        params.put("partnerid", SaiheyiConstants.PARENT_ID);
        params.put("timestamp", timestamp);
        params.put("productid", productid);
        params.put("delayfee", delayfee);
//        params.put("noticeurl", SaiheyiConstants.NOTICE_URL);
        params.put("stockordernumber", stockordernumber);
        params.put("timeout", SaiheyiConstants.TIME_OUT);
        params.put("wecaccount", wecaccount);
        params.put("wecbillmoney", wecbillmoney);

        String sign = params.sign(SaiheyiConstants.SIGN_KEY);
        Map<String, String> stringMap = new HashMap<String, String>();
        stringMap.put("actionname", SaiheyiConstants.WEC_RECHARGE);
        stringMap.put("partnerid", SaiheyiConstants.PARENT_ID);
        stringMap.put("timestamp", timestamp);
        stringMap.put("productid", productid);
        stringMap.put("delayfee", delayfee);
//        stringMap.put("noticeurl", SaiheyiConstants.NOTICE_URL);
        stringMap.put("stockordernumber", stockordernumber);
        stringMap.put("timeout", SaiheyiConstants.TIME_OUT);
        stringMap.put("wecaccount", wecaccount);
        stringMap.put("wecbillmoney", wecbillmoney);
        stringMap.put("sign", sign); //签名
        HttpClientResult httpClientResult = null;
        try {
            httpClientResult = HttpClientUtils.doPost(SaiheyiConstants.URL, stringMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpClientResult;
    }

    @Override
    public HttpClientResult orderStatus(String stockordernumber) {
        logger.info("[缴费查询] 商户订单号：{}", stockordernumber);
        String timestamp = DateUtils.getCurrentDateStr();
        ParameterBuilder params = new ParameterBuilder();
        params.put("actionname", SaiheyiConstants.ORDER_STATUS);
        params.put("partnerid", SaiheyiConstants.PARENT_ID);
        params.put("timestamp", timestamp);
        params.put("stockordernumber", stockordernumber);
        String sign = params.sign(SaiheyiConstants.SIGN_KEY);
        Map<String, String> stringMap = new HashMap<String, String>();
        stringMap.put("actionname", SaiheyiConstants.ORDER_STATUS);
        stringMap.put("partnerid", SaiheyiConstants.PARENT_ID);
        stringMap.put("timestamp", timestamp);
        stringMap.put("stockordernumber", stockordernumber);
        stringMap.put("sign", sign); //签名
        HttpClientResult httpClientResult = null;
        try {
            httpClientResult = HttpClientUtils.doPost(SaiheyiConstants.URL, stringMap);
        } catch (Exception e) {
            httpClientResult = new HttpClientResult(HttpConstant.HTTP_CODE_SERVER_ERROR, null);
        }
        return httpClientResult;
    }

    @Override
    public RequestResult prepayment(String wecaccount,String latefee, String wecbillmoney, Integer type) {
        List<RechargeAccount> rechargeAccountList = rechargeAccountMapper.selectRechargeAccountByWecAccount(wecaccount, type.byteValue());
        if (CollectionUtils.isEmpty(rechargeAccountList)) {
            return new RequestResult(HttpConstant.HTTP_CODE_SAVE_ERROR, "户号缴费信息已经存在", null);
        }
        RechargeAccount rechargeAccount = rechargeAccountList.get(0);
        HttpClientResult result = wrecharge(rechargeAccount.getProductId(), latefee, wecaccount, wecbillmoney);
        PaymentRecord paymentRecord = null;
        if (result == null || result.getCode() != 200) {
            return new RequestResult(HttpConstant.HTTP_CODE_SAVE_ERROR, "户号缴费失败", null);
        } else {
            WecbillpostVO wecbillpostVO = JSONObject.parseObject(result.getContent(), WecbillpostVO.class);
            paymentRecord = new PaymentRecord();
            Byte status = 5;
            if ("true".equals(wecbillpostVO.getStatus())) {
                status = 3;
                paymentRecord.setRechargeOrderNumber(wecbillpostVO.getContent().getStockordernumber());
                paymentRecord.setStatus(status);
                paymentRecord.setWecAccount(wecaccount);
                paymentRecord.setWecType(type.byteValue());
                paymentRecord.setBillMoney(new BigDecimal(wecbillmoney));
                paymentRecord.setLateFee(new BigDecimal(latefee));
                paymentRecord.setRechageTime(new Date());
                paymentRecord.setDescription("[缴费]:" + wecbillpostVO.getMessage());
                paymentRecordMapper.insertSelective(paymentRecord);
            }else {
                return new RequestResult(HttpConstant.HTTP_CODE_SAVE_ERROR, "户号缴费失败", null);
            }

        }

        return new RequestResult(HttpConstant.HTTP_CODE_SUCCESS, "户号缴费成功", null);
    }


}
